package com.zhangcuishan.blog.controller;

import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.CompletionChoice;
import com.theokanning.openai.completion.CompletionRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@CrossOrigin
@RestController
public class OpenAiController {

    @Autowired
    private OpenAiService openAiService;

    @GetMapping("/")
    public String index() {
        return "Hello OpenAi";
    }

    @GetMapping("/chat")
    public Object chat(@RequestParam(name = "question", required = false) String question) {


        if(StringUtils.isEmpty(question)) {
            question = "你好";
        }

        CompletionRequest request = CompletionRequest.builder()
                .model("text-davinci-003")
                .prompt(question)
                .temperature(0D)
                .maxTokens(1000)
                .topP(1D)
                .frequencyPenalty(0D)
                .presencePenalty(0D)
                .build();

        List<CompletionChoice> choices = openAiService.createCompletion(request).getChoices();
        choices.forEach(System.out::println);
        return choices;
    }
}
